package com.example.bianproject;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.bianproject.Adapter.UAdapter;
import com.example.bianproject.Constants.HttpConstants;
import com.example.bianproject.Model.UContractModel;
import com.example.bianproject.Model.UModel;
import com.example.bianproject.Model.UPriceModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView mU_RecyclerView, mB_RecyclerView;
    private Button mU_Btn, mB_Btn;
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();
    private List<UContractModel> mUContractModelList = new ArrayList<>();
    private List<UPriceModel> mUPriceModelList = new ArrayList<>();
    private List<UModel> mUModelList = new ArrayList<>();
    private Type mUContractType = new TypeToken<UContractModel>() {
    }.getType();
    private Type mUPriceType = new TypeToken<UPriceModel>() {
    }.getType();
    //    private final Retrofit retrofit = new Retrofit.Builder()
//            .baseUrl(HttpConstants.BASE_URL)
//            .addConverterFactory(GsonConverterFactory.create())
//            .build();
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        initHttp();
    }

    private void initHttp() {
        okHttpClient = new OkHttpClient();
    }

    private void initUI() {
        mU_RecyclerView = findViewById(R.id.U_RecyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mU_RecyclerView.setLayoutManager(layoutManager);
        mB_RecyclerView = findViewById(R.id.B_RecyclerView);
        mU_Btn = findViewById(R.id.U_button);
        mU_Btn.setOnClickListener(this);
        mB_Btn = findViewById(R.id.B_button);
        mB_Btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.U_button:
                // TODO 这里切换Fragment  请求网络数据并展示
                mU_RecyclerView.setVisibility(View.VISIBLE);
                mB_RecyclerView.setVisibility(View.GONE);
                mU_Btn.setBackgroundColor(getResources().getColor(R.color.press_btn));
                mB_Btn.setBackgroundColor(getResources().getColor(R.color.default_btn));
                for (int i = 0; i < HttpConstants.SYMBOL_LIST.size(); i++) {
                    getUDataTask(i);
                }
                Log.i(TAG, mUModelList.size()+"size");
                UAdapter adapter = new UAdapter(mUModelList);
                mU_RecyclerView.setAdapter(adapter);
                break;
            case R.id.B_button:
                // TODO 这里切换Fragment  请求网络数据并展示
                mB_RecyclerView.setVisibility(View.VISIBLE);
                mU_RecyclerView.setVisibility(View.GONE);
                mU_Btn.setBackgroundColor(getResources().getColor(R.color.default_btn));
                mB_Btn.setBackgroundColor(getResources().getColor(R.color.press_btn));
                break;
        }
    }

    private void getUDataTask(int index) {
        Observable.just(HttpConstants.BASE_URL + HttpConstants.U_CONTRACT_URL)
                // 需求：获取合约价格
                .map(new Function<String, List<UContractModel>>() {
                    @Override
                    public List<UContractModel> apply(String s) throws Exception {
                        return getUContractSync(index);
                    }
                })
                // 给上面的分配异步线程
                .subscribeOn(Schedulers.io())
                // 获取现价价格
                .map(new Function<List<UContractModel>, List<UPriceModel>>() {
                    @Override
                    public List<UPriceModel> apply(List<UContractModel> uContractModels) throws Exception {
                        return getUPriceSync(index);
                    }
                })
                .subscribeOn(Schedulers.io())
                .map(new Function<List<UPriceModel>, UModel>() {
                    @Override
                    public UModel apply(List<UPriceModel> uPriceModels) throws Exception {
                        float minus = Math.abs((mUPriceModelList.get(index).getPrice() - mUContractModelList.get(index).getPrice()) / 1000);
//                                    minus = (float)(Math.round(minus*100000)/100000.0);
                        String decimal = new DecimalFormat("#.####").format(minus);
                        if (!decimal.equals(""))
                            minus = Float.parseFloat(decimal);
                        if (minus > 3.0 / 1000) {
                            UModel uModel = new UModel();
                            uModel.setName(mUContractModelList.get(index).getSymbol());
                            uModel.setContract(mUContractModelList.get(index).getPrice() + "");
                            uModel.setPrice(mUPriceModelList.get(index).getPrice() + "");
                            uModel.setMinus(minus + "");
                            Log.i(TAG, "币种 = " + uModel.getName() +
                                    " | 合约 = " + uModel.getContract() +
                                    " | 现价 = " + uModel.getPrice() +
                                    " | 差价 = " + minus);
//                            mUModelList.add(uModel);
                            return uModel;
                        }
                        return null;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //关联：观察者设计模式   关联起点和终点 == 订阅
                .subscribe(new Observer<UModel>() {
                    // 订阅成功
                    @Override
                    public void onSubscribe(Disposable d) {
                        //正在加载中

                    }

                    // 上一层给我的响应
                    @Override
                    public void onNext(UModel uModel) {
                        if(uModel != null){
                            mUModelList.add(uModel);
                        }
                    }

                    // 链条发生了异常
                    @Override
                    public void onError(Throwable e) {

                    }

                    // 整个链条全部结束
                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取所有合约数据的同步请求方法
     */
    private List<UContractModel> getUContractSync(int index) {
        mUContractModelList.clear();
        Request request = new Request.Builder().url(HttpConstants.BASE_URL +
                HttpConstants.U_CONTRACT_URL + "?symbol=" + HttpConstants.SYMBOL_LIST.get(index)).build();
        Call call = (Call) okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String responseString = response.body().string();
            mUContractModelList.add(gson.fromJson(responseString, mUContractType));
        } catch (IOException e) {
            e.printStackTrace();
        }

//        Request request = new Request.Builder().url(HttpConstants.BASE_URL + HttpConstants.U_CONTRACT_URL).build();
//        Call call = (Call) okHttpClient.newCall(request);
//        try {
//            Response response = call.execute();
//            String responseString = response.body().string();
//            mContractModelList = gson.fromJson(responseString, mUContractType);
//            Collections.sort(mContractModelList, new Comparator<UContractModel>() {
//                @Override
//                public int compare(UContractModel o1, UContractModel o2) {
//                    return o1.getSymbol().compareTo(o2.getSymbol());
//                }
//            });
//            Log.i(TAG, mContractModelList.size() + "");
//            Log.i(TAG, responseString);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return mUContractModelList;

    }


    /**
     * 获取所有现货数据的同步请求方法
     */
    private List<UPriceModel> getUPriceSync(int index) {
        mUPriceModelList.clear();
        Request request = new Request.Builder().url(HttpConstants.BASE_URL +
                HttpConstants.U_PRICE_URL + "?symbol=" + HttpConstants.SYMBOL_LIST.get(index)).build();
        Call call = (Call) okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String responseString = response.body().string();
            mUPriceModelList.add(gson.fromJson(responseString, mUPriceType));
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Log.i(TAG, mPriceModelList.size() + " mPrice");


//        Request request = new Request.Builder().url(HttpConstants.BASE_URL + HttpConstants.U_PRICE_URL).build();
//        Call call = (Call) okHttpClient.newCall(request);
//        try {
//            Response response = call.execute();
//            String responseString = response.body().string();
//            mPriceModelList = gson.fromJson(responseString, mUPriceType);
//            Log.i(TAG, mPriceModelList.size() + "");
//            Log.i(TAG, responseString);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return mUPriceModelList;
    }
}